package ThreadCommunication;

public class SignalLight
{
    public static void main(String[] args)
    {
        Resource resource=new Resource();
        new Produce(resource).start();
        new Consume(resource).start();
    }
}

//生产者
class Produce extends Thread
{
    Resource resource;
    public Produce(Resource resource)
    {
        this.resource=resource;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 10; i++)
        {
            if (i%2==0)
            {
                this.resource.play("A action");
            }else {
                this.resource.play("B action");
            }
        }
    }
}
//消费者
class Consume extends Thread
{
    Resource resource;
    public Consume(Resource resource)
    {
        this.resource=resource;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 100; i++)
        {
            resource.watch();
        }
    }
}
//资源
class Resource
{
    String show;
    Boolean flag=true;//进程是否被操作,T代表消费者等待

    public synchronized void play(String show)
    {
        //如果正在观看，则等待
        if (!flag)
        {
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println("Do"+show);
        //通知消费者
        this.notifyAll();
        this.show=show;
        this.flag=!this.flag;
    }
    public synchronized void watch()
    {
        if (flag)
        {
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println("Consumed"+show);
        //通知生产
        this.notifyAll();
        this.flag=!this.flag;
    }

}
